package com.example.zwlyz;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.zwlyz.adapters.CartAdapter;
import com.example.zwlyz.adapters.CartAdapter.OnCartItemClickListener;
import com.example.zwlyz.models.CartItem;
import com.example.zwlyz.R;

import java.util.List;

public class CartActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private CartAdapter cartAdapter;
    private TextView tvTotal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        recyclerView = findViewById(R.id.recyclerView);
        tvTotal = findViewById(R.id.tvTotal);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 获取购物车数据
        List<CartItem> cartItems = CartManager.getAllCartItems();

        if (cartItems != null && !cartItems.isEmpty()) {
            cartAdapter = new CartAdapter(cartItems, new OnCartItemClickListener() {
                @Override
                public void onCartItemChanged() {
                    updateTotalPrice(cartItems);
                }
            });
            recyclerView.setAdapter(cartAdapter);

            updateTotalPrice(cartItems);
        } else {
            tvTotal.setText("总计: ￥0.00");
        }
    }

    private void updateTotalPrice(List<CartItem> cartItems) {
        double total = 0.0;
        for (CartItem item : cartItems) {
            total += item.getPrice() * item.getQuantity();
        }
        tvTotal.setText(String.format("总计: ￥%.2f", total));
    }
}